package middlewares

import (
	"os"
	"strings"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
)

const (
	maxAge = 12
)

// Cors add cors headers.
func Cors() gin.HandlerFunc {
	config := cors.Config{
		AllowMethods: []string{
			"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS",
		},
		AllowHeaders: []string{
			"Origin",
			"Content-Length",
			"Content-Type",
			"Accept",
			"Authorization",
			"X-Requested-With",
			"X-HTTP-Method-Override",
			"Cache-Control",
			"Accept-Encoding",
			"Accept-Language",
			"Connection",
			"User-Agent",
		},
		ExposeHeaders: []string{
			"Content-Length",
			"Content-Type",
			"Authorization",
		},
		AllowCredentials: true,
		MaxAge:           maxAge * time.Hour,
	}

	// 根据环境变量决定CORS策略
	env := os.Getenv("ENV")
	if env == "production" {
		// 生产环境：限制特定域名
		allowedOrigins := os.Getenv("ALLOWED_ORIGINS")
		if allowedOrigins != "" {
			origins := strings.Split(allowedOrigins, ",")
			config.AllowOriginFunc = func(origin string) bool {
				for _, allowedOrigin := range origins {
					if strings.TrimSpace(allowedOrigin) == origin {
						return true
					}
				}
				return false
			}
		} else {
			// 如果没有设置环境变量，默认允许常见的生产域名
			config.AllowOriginFunc = func(origin string) bool {
				return strings.HasSuffix(origin, ".yourdomain.com") ||
					origin == "https://yourdomain.com"
			}
		}
	} else {
		// 开发环境：允许所有来源
		config.AllowOriginFunc = func(origin string) bool {
			// 开发环境允许localhost和127.0.0.1的所有端口
			return strings.Contains(origin, "localhost") ||
				strings.Contains(origin, "127.0.0.1") ||
				strings.Contains(origin, "192.168.") ||
				strings.Contains(origin, "10.0.") ||
				origin == "" // 允许某些开发工具的空origin
		}
	}

	return cors.New(config)
}
